import React, { useMemo, useState, useRef, useEffect } from 'react';
import { Button, MessagePlugin, DatePicker } from 'tdesign-react';
import { useAuth } from '../../../shared/state/auth';
import { updateUserInfo, updateAvatar, getCurrentUserInfo, getUserPreferences, updateUserPreferences, resetUserPreferences } from '../../../shared/api/user';
import { fetchIpLocation } from '../../utils/ip';
import { formatDateTime } from '../../utils/date';
import { UserIcon, AdjustmentIcon, LocationIcon, DragDropIcon ,AddressBookIcon ,DeleteTimeIcon } from 'tdesign-icons-react';

const Card = ({ children, style }) => (
  <div style={{ background: 'var(--card)', border: '1px solid var(--border)', borderRadius: '12px', boxShadow: '0 4px 6px -1px rgba(0,0,0,0.05), 0 2px 4px -1px rgba(0,0,0,0.03)', padding: '16px', ...style }}>{children}</div>
);

const Chip = ({ active, onClick, children }) => (
  <button
    onClick={onClick}
    style={{
      height: 40,
      padding: '0 14px',
      borderRadius: 20,
      border: `1px solid ${active ? 'var(--text)' : 'var(--border)'}`,
      background: active ? 'var(--text)' : 'var(--card)',
      color: active ? 'var(--bg)' : 'var(--text)'
    }}
  >
    {children}
  </button>
);

const Sidebar = ({ current, onChange, user }) => {
  return (
  <div className="profile-sidebar" style={{ width: 240, background: 'var(--card)', borderRight: 'none', minHeight: 'calc(100vh - 64px)' }}>
    <div style={{ padding: '16px 20px 8px', display: 'flex', flexDirection: 'column', gap: 12, marginTop: -4 }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
        <div style={{ width: 56, height: 56, borderRadius: '50%', overflow: 'hidden' }}>
          <img
            src={user?.avatar || '/person.svg'}
            alt="avatar"
            style={{ width: '100%', height: '100%', objectFit: 'cover' }}
          />
        </div>
        <div>
          <div style={{ fontWeight: 600, color: 'var(--text)' }}>{user?.nickname || user?.username || '未登录用户'}</div>
          <div style={{ color: 'var(--muted)', fontSize: 13 }}>{user?.bio || ''}</div>
        </div>
      </div>
      <div style={{ marginTop: 24, display: 'flex', flexDirection: 'column', gap: 6 }}>
        {[
          { key: 'info', label: '个人信息', icon: <UserIcon fillColor='transparent' strokeColor='currentColor' strokeWidth={1.5} /> },
          { key: 'prefs', label: '偏好设置', icon: <AdjustmentIcon fillColor='transparent' strokeColor='currentColor' strokeWidth={1.5}/> },
          { key: 'checkin', label: '打卡记录', icon: <LocationIcon fillColor='transparent' strokeColor='currentColor' strokeWidth={1.5}/> },
          { key: 'posts', label: '发布帖子', icon: <DragDropIcon fillColor='transparent' strokeColor='currentColor' strokeWidth={1.5}/> },
          { key: 'collections', label: '收藏内容', icon: <AddressBookIcon fillColor='transparent' strokeColor='currentColor' strokeWidth={1.5}/> },
          { key: 'trash', label: '回收站', icon: <DeleteTimeIcon fillColor='transparent' strokeColor='currentColor' strokeWidth={1.5}/> },
        ].map(item => (
          <button
            key={item.key}
            onClick={() => onChange(item.key)}
            style={{
              height: 42,
              textAlign: 'left',
              borderRadius: 8,
              padding: '0 16px',
              background: current === item.key ? 'var(--text)' : 'transparent',
              color: current === item.key ? 'var(--bg)' : 'var(--text)',
              fontSize: 15,
              border: 'none',
              cursor: 'pointer',
              display: 'flex',
              alignItems: 'center',
              gap: 8,
            }}
          >
            {item.icon}
            {item.label}
          </button>
        ))}
      </div>
    </div>
  </div>
  );
};

const Input = ({ label, value, onChange, type = 'text', placeholder }) => (
  <div style={{ display: 'grid', gridTemplateColumns: '180px 1fr', alignItems: 'center', gap: 12 }}>
    <div style={{ color: 'var(--muted)' }}>{label}</div>
    <input
      type={type}
      value={value}
      onChange={e => onChange(e.target.value)}
      placeholder={placeholder}
      style={{ height: 40, borderRadius: 12, border: '1px solid var(--border)', background: 'var(--card)', color: 'var(--text)', padding: '0 12px', outline: 'none' }}
    />
  </div>
);

const TextArea = ({ label, value, onChange, placeholder }) => (
  <div style={{ display: 'grid', gridTemplateColumns: '180px 1fr', gap: 12 }}>
    <div style={{ color: 'var(--muted)', alignSelf: 'start' }}>{label}</div>
    <textarea
      value={value}
      onChange={e => onChange(e.target.value)}
      placeholder={placeholder}
      style={{ minHeight: 96, borderRadius: 12, border: '1px solid var(--border)', background: 'var(--card)', color: 'var(--text)', padding: 12, outline: 'none', resize: 'vertical' }}
    />
  </div>
);

const ProfileInfo = () => {
  const { user, updateUser } = useAuth();
  const [ipLocation, setIpLocation] = useState('');
  const [editing, setEditing] = useState(false);
  const [form, setForm] = useState(() => ({
    id: user?.id || '',
    username: user?.username || '',
    avatar: user?.avatar || '',
    nickname: user?.nickname || '',
    gender: user?.gender ?? '',
    birthday: user?.birthday || '',
    email: user?.email || '',
    phone: user?.phone || '',
    bio: user?.bio || ''
  }));
  const [selectedFile, setSelectedFile] = useState(null);
  const fileRef = useRef(null);

  const validate = () => {
    if (!form.nickname || form.nickname.length < 2 || form.nickname.length > 20) return '昵称长度需 2-20';
    if (form.email && !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(form.email)) return '邮箱格式不正确';
    if (form.phone && form.phone.replace(/\D/g, '').length < 7) return '手机号格式不正确';
    if (form.birthday && isNaN(Date.parse(form.birthday))) return '生日日期不合法';
    const g = String(form.gender);
    if (g && !['0','1','2'].includes(g)) return '性别取值不合法';
    return null;
  };

  const onSave = async () => {
    const err = validate();
    if (err) { MessagePlugin.warning(err); return; }
    // 如果存在未确认的头像选择，先上传头像
    if (selectedFile) {
      try {
        const res = await updateAvatar(selectedFile);
        const raw = (typeof res === 'string') ? res : (res?.avatar || '');
        const url = String(raw).replace(/[`'\"]+/g, '').trim();
        setSelectedFile(null);
        setForm(prev => ({ ...prev, avatar: url || prev.avatar }));
        updateUser({ ...(user || {}), avatar: url || (user?.avatar || '') });
      } catch {
        MessagePlugin.warning('头像上传失败');
      }
    }

    const payload = {
      id: form.id,
      username: form.username,
      nickname: form.nickname,
      email: form.email,
      phone: form.phone,
      gender: form.gender === '' ? '' : String(form.gender),
      birthday: form.birthday || '',
      bio: form.bio || '',
    };
    try {
      await updateUserInfo(payload);
      try {
        const refreshed = await getCurrentUserInfo();
        updateUser(refreshed || { ...(user || {}), ...payload });
      } catch {
        updateUser({ ...(user || {}), ...payload });
      }
      MessagePlugin.success('保存成功');
      setEditing(false);
    } catch {
      updateUser({ ...(user || {}), ...payload });
      MessagePlugin.success('保存成功');
      setEditing(false);
    }
  };

  const onPickFile = () => fileRef.current?.click();
  const onFileChange = e => {
    const file = e.target.files?.[0];
    if (!file) return;
    setSelectedFile(file);
    const reader = new FileReader();
    reader.onload = () => setForm(prev => ({ ...prev, avatar: String(reader.result) }));
    reader.readAsDataURL(file);
  };

  const onConfirmUpload = async () => {
    if (!selectedFile) return;
    try {
      const res = await updateAvatar(selectedFile);
      const raw = (typeof res === 'string') ? res : (res?.avatar || '');
      const url = String(raw).replace(/[`'\"]+/g, '').trim();
      setSelectedFile(null);
      setForm(prev => ({ ...prev, avatar: url || prev.avatar }));
      updateUser({ ...(user || {}), avatar: url || (user?.avatar || '') });
      MessagePlugin.success('头像已更新');
    } catch {
      MessagePlugin.warning('头像更新失败');
    }
  };

  useEffect(() => {
    let mounted = true;
    (async () => {
      if (user?.lastLoginIp) {
        try {
          const loc = await fetchIpLocation(user.lastLoginIp);
          if (mounted) setIpLocation(loc || '');
        } catch {
          if (mounted) setIpLocation('');
        }
      } else {
        setIpLocation('');
      }
    })();
    return () => { mounted = false; };
  }, [user?.lastLoginIp]);

  return (
  <Card style={{ padding: '32px 40px' }}>
    <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
      <div>
        <div style={{ fontSize: 18, fontWeight: 600, color: 'var(--text)' }}>个人信息</div>
        <div style={{ color: 'var(--muted)', fontSize: 14, marginTop: 4 }}>管理您的个人资料，确保信息准确无误。</div>
      </div>
      {!editing ? (
        <Button
          onClick={() => setEditing(true)}
          style={{
            background: 'var(--text)',
            color: 'var(--bg)',
            borderRadius: 6,
            height: 36,
            padding: '0 20px',
          }}
        >
          编辑
        </Button>
      ) : (
        <div style={{ display: 'flex', gap: 8 }}>
          <Button variant="outline" onClick={() => setEditing(false)} style={{ height: 36 }}>
            取消
          </Button>
          <Button onClick={onSave} style={{ height: 36, background: 'var(--text)', color: 'var(--bg)' }}>
            保存
          </Button>
        </div>
      )}
    </div>

    <div style={{ marginTop: 32 }}>
      {editing ? (
        <>
          <div style={{ display: 'grid', gridTemplateColumns: '120px 1fr', alignItems: 'center', padding: '16px 0' }}>
            <div style={{ color: 'var(--muted)', fontSize: 14 }}>头像</div>
            <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
              <div style={{ width: 56, height: 56, borderRadius: '50%', overflow: 'hidden' }}>
                <img src={form.avatar || '/person.svg'} alt="avatar" style={{ width: '100%', height: '100%', objectFit: 'cover' }} />
              </div>
              <input ref={fileRef} type="file" accept="image/*" onChange={onFileChange} style={{ display: 'none' }} />
              {!selectedFile ? (
                <Button variant="outline" onClick={onPickFile} style={{ height: 36 }}>上传</Button>
              ) : (
                <Button onClick={onConfirmUpload} style={{ height: 36, background: 'var(--text)', color: 'var(--bg)' }}>确认</Button>
              )}
          </div>
        </div>
          <div style={{ display: 'grid', gridTemplateColumns: '120px 1fr', alignItems: 'center', padding: '16px 0', borderTop: '1px solid var(--border)' }}>
            <div style={{ color: 'var(--muted)', fontSize: 14 }}>昵称</div>
            <input type="text" value={form.nickname} onChange={e => setForm(s => ({ ...s, nickname: e.target.value }))} style={{ height: 40, border: '1px solid var(--border)', borderRadius: 12, padding: '0 12px', outline: 'none' }} />
          </div>
          <div style={{ display: 'grid', gridTemplateColumns: '120px 1fr', alignItems: 'center', padding: '16px 0', borderTop: '1px solid var(--border)' }}>
            <div style={{ color: 'var(--muted)', fontSize: 14 }}>性别</div>
            <div style={{ display: 'flex', gap: 8 }}>
              {[{ code: '0', label: '未知' }, { code: '1', label: '男' }, { code: '2', label: '女' }].map(g => (
                <Chip key={g.code} active={String(form.gender) === g.code} onClick={() => setForm(s => ({ ...s, gender: g.code }))}>{g.label}</Chip>
              ))}
            </div>
          </div>
          <div style={{ display: 'grid', gridTemplateColumns: '120px 1fr', alignItems: 'center', padding: '16px 0', borderTop: '1px solid var(--border)' }}>
            <div style={{ color: 'var(--muted)', fontSize: 14 }}>生日</div>
            <DatePicker
              mode="date"
              allowInput={true}
              value={form.birthday || undefined}
              format="YYYY-MM-DD"
              onChange={(v) => {
                let next = '';
                if (typeof v === 'string') next = v;
                else if (v && typeof v === 'object') {
                  try { next = v.format ? v.format('YYYY-MM-DD') : ''; } catch { next = ''; }
                }
                setForm(s => ({ ...s, birthday: next }));
              }}
              style={{ height: 40 }}
            />
          </div>
          <div style={{ display: 'grid', gridTemplateColumns: '120px 1fr', alignItems: 'center', padding: '16px 0', borderTop: '1px solid var(--border)' }}>
            <div style={{ color: 'var(--muted)', fontSize: 14 }}>电子邮箱</div>
            <input type="email" value={form.email} onChange={e => setForm(s => ({ ...s, email: e.target.value }))} style={{ height: 40, border: '1px solid var(--border)', borderRadius: 12, padding: '0 12px', outline: 'none' }} />
          </div>
          <div style={{ display: 'grid', gridTemplateColumns: '120px 1fr', alignItems: 'center', padding: '16px 0', borderTop: '1px solid var(--border)' }}>
            <div style={{ color: 'var(--muted)', fontSize: 14 }}>手机号码</div>
            <input type="text" value={form.phone} onChange={e => setForm(s => ({ ...s, phone: e.target.value }))} style={{ height: 40, border: '1px solid var(--border)', borderRadius: 12, padding: '0 12px', outline: 'none' }} />
          </div>
          <div style={{ display: 'grid', gridTemplateColumns: '120px 1fr', padding: '16px 0', borderTop: '1px solid var(--border)' }}>
            <div style={{ color: 'var(--muted)', fontSize: 14 }}>个人简介</div>
            <textarea value={form.bio} onChange={e => setForm(s => ({ ...s, bio: e.target.value }))} style={{ minHeight: 96, border: '1px solid var(--border)', borderRadius: 12, padding: 12, outline: 'none' }} />
          </div>
        </>
      ) : (
        [
          { label: '头像', value: user?.avatar },
          { label: '用户名', value: user?.username },
          { label: '昵称', value: user?.nickname },
          { label: '性别', value: (String(user?.gender) === '1' ? '男' : (String(user?.gender) === '2' ? '女' : '未知')) },
          { label: '生日', value: user?.birthday },
          { label: '电子邮箱', value: user?.email },
          { label: '手机号码', value: user?.phone },
          { label: '最近登录IP地址', value: ipLocation || '未知' },
          { label: '最近登录时间', value: formatDateTime(user?.lastLoginTime) },
        ].map((item, i) => (
          <div
            key={item.label}
            style={{ display: 'grid', gridTemplateColumns: '120px 1fr', alignItems: 'center', padding: '16px 0', borderTop: i !== 0 ? '1px solid var(--border)' : 'none' }}
          >
            <div style={{ color: 'var(--muted)', fontSize: 14 }}>{item.label}</div>
            {item.label === '头像' ? (
              <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
                <div style={{ width: 56, height: 56, borderRadius: '50%', overflow: 'hidden' }}>
                  <img src={user?.avatar || '/person.svg'} alt="avatar" style={{ width: '100%', height: '100%', objectFit: 'cover' }} />
                </div>
              </div>
            ) : (
              <div style={{ color: 'var(--text)', fontSize: 14 }}>{item.value || '-'}</div>
            )}
          </div>
        ))
      )}
    </div>
  </Card>
);

};

const PreferencesStoreKey = 'nexusgo.profile.preferences';

const TravelPreferences = () => {
  const [pref, setPref] = useState({
    travelStyle: [],
    accommodationType: [],
    transportPreference: [],
    foodPreference: [],
    travelCompanions: 'solo',
    budgetRange: 1500,
    languagePreference: 'zh-CN',
    timezone: 'Asia/Shanghai',
    privacySettings: { profile_visibility: 'public', checkin_visibility: 'friends_only', allow_stranger_messages: false, show_online_status: true },
    notificationSettings: { msg_notify: true, like_notify: true, follow_notify: true },
  });

  const parseSet = (s) => String(s || '').split(',').filter(Boolean);
  const toSet = (arr) => (arr || []).join(',');

  React.useEffect(() => {
    (async () => {
      try {
        const data = await getUserPreferences();
        let privacy = {};
        let notify = {};
        try { privacy = JSON.parse(String(data?.privacySettings || '{}')); } catch { privacy = {}; }
        try { notify = JSON.parse(String(data?.notificationSettings || '{}')); } catch { notify = {}; }
        setPref({
          travelStyle: parseSet(data?.travelStyle),
          accommodationType: parseSet(data?.accommodationType),
          transportPreference: parseSet(data?.transportPreference),
          foodPreference: parseSet(data?.foodPreference),
          travelCompanions: String(data?.travelCompanions || 'solo'),
          budgetRange: Number(data?.budgetRange || 1500),
          languagePreference: String(data?.languagePreference || 'zh-CN'),
          timezone: String(data?.timezone || 'Asia/Shanghai'),
          privacySettings: {
            profile_visibility: String(privacy?.profile_visibility || 'public'),
            checkin_visibility: String(privacy?.checkin_visibility || 'friends_only'),
            allow_stranger_messages: Boolean(privacy?.allow_stranger_messages ?? false),
            show_online_status: Boolean(privacy?.show_online_status ?? true),
          },
          notificationSettings: {
            msg_notify: Boolean(notify?.msg_notify ?? true),
            like_notify: Boolean(notify?.like_notify ?? true),
            follow_notify: Boolean(notify?.follow_notify ?? true),
          },
        });
      } catch {}
    })();
  }, []);

  const save = async () => {
    const payload = {
      travelStyle: toSet(pref.travelStyle),
      accommodationType: toSet(pref.accommodationType),
      transportPreference: toSet(pref.transportPreference),
      foodPreference: toSet(pref.foodPreference),
      travelCompanions: pref.travelCompanions,
      budgetRange: Number(pref.budgetRange || 0),
      languagePreference: pref.languagePreference,
      timezone: pref.timezone,
      interestTags: '[]',
      preferredCities: '[]',
      avoidCities: '[]',
      privacySettings: JSON.stringify(pref.privacySettings || {}),
      notificationSettings: JSON.stringify(pref.notificationSettings || {}),
    };
    try {
      await updateUserPreferences(payload);
      MessagePlugin.success('保存成功');
    } catch {
      MessagePlugin.warning('保存失败');
    }
  };

  const reset = async () => {
    try {
      const data = await resetUserPreferences();
      let privacy = {};
      let notify = {};
      try { privacy = JSON.parse(String(data?.privacySettings || '{}')); } catch { privacy = {}; }
      try { notify = JSON.parse(String(data?.notificationSettings || '{}')); } catch { notify = {}; }
      setPref({
        travelStyle: parseSet(data?.travelStyle),
        accommodationType: parseSet(data?.accommodationType),
        transportPreference: parseSet(data?.transportPreference),
        foodPreference: parseSet(data?.foodPreference),
        travelCompanions: String(data?.travelCompanions || 'solo'),
        budgetRange: Number(data?.budgetRange || 0),
        languagePreference: String(data?.languagePreference || 'zh-CN'),
        timezone: String(data?.timezone || 'Asia/Shanghai'),
        privacySettings: {
          profile_visibility: String(privacy?.profile_visibility || 'public'),
          checkin_visibility: String(privacy?.checkin_visibility || 'friends_only'),
          allow_stranger_messages: Boolean(privacy?.allow_stranger_messages ?? false),
          show_online_status: Boolean(privacy?.show_online_status ?? true),
        },
        notificationSettings: {
          msg_notify: Boolean(notify?.msg_notify ?? true),
          like_notify: Boolean(notify?.like_notify ?? true),
          follow_notify: Boolean(notify?.follow_notify ?? true),
        },
      });
      MessagePlugin.success('已重置');
    } catch {
      MessagePlugin.warning('重置失败');
    }
  };

  const toggleArr = (key, val) => {
    const arr = pref[key] || [];
    const next = arr.includes(val) ? arr.filter(i => i !== val) : [...arr, val];
    setPref(p => ({ ...p, [key]: next }));
  };

  const TravelStyles = [
    { code: 'adventure', label: '探险' },
    { code: 'leisure', label: '休闲' },
    { code: 'cultural', label: '文化' },
    { code: 'foodie', label: '美食' },
    { code: 'shopping', label: '购物' },
    { code: 'photography', label: '摄影' },
    { code: 'roadtrip', label: '自驾' },
  ];
  const Accommodation = [
    { code: 'hotel', label: '酒店' },
    { code: 'hostel', label: '青年旅社' },
    { code: 'bnb', label: '民宿' },
    { code: 'resort', label: '度假村' },
    { code: 'camping', label: '露营' },
  ];
  const Transport = [
    { code: 'flight', label: '飞机' },
    { code: 'train', label: '火车' },
    { code: 'bus', label: '巴士' },
    { code: 'car', label: '自驾' },
    { code: 'bike', label: '骑行' },
    { code: 'walking', label: '步行' },
  ];
  const Food = [
    { code: 'local', label: '本地' },
    { code: 'international', label: '国际' },
    { code: 'vegetarian', label: '素食' },
    { code: 'vegan', label: '纯素' },
    { code: 'halal', label: '清真' },
    { code: 'kosher', label: '犹太洁食' },
  ];
  const Companions = [
    { code: 'solo', label: '独自' },
    { code: 'couple', label: '情侣' },
    { code: 'family', label: '家庭' },
    { code: 'friends', label: '朋友' },
    { code: 'group', label: '团体' },
    { code: 'business', label: '商务' },
  ];
  const Languages = [
    { code: 'zh-CN', label: '中文（简体）' },
    { code: 'zh-TW', label: '中文（繁体）' },
    { code: 'en-US', label: '英语' },
    { code: 'ja-JP', label: '日语' },
    { code: 'ko-KR', label: '韩语' },
  ];
  const Timezones = [
    { code: 'Asia/Shanghai', label: '中国标准时间' },
    { code: 'Asia/Tokyo', label: '日本（东京）' },
    { code: 'Asia/Seoul', label: '韩国（首尔）' },
    { code: 'Europe/Zurich', label: '欧洲（苏黎世）' },
    { code: 'Europe/Rome', label: '欧洲（罗马）' },
    { code: 'Asia/Singapore', label: '新加坡' },
  ];

  return (
    <Card>
      <div style={{ display: 'flex', flexDirection: 'column' }}>
        <div style={{ color: 'var(--text)', fontWeight: 800, fontSize: 18 }}>偏好设置设置</div>
        <div style={{ color: 'var(--muted)', fontSize: 14, marginTop: 6 }}>告诉我们您喜欢什么，以便我们为您量身推荐。</div>
      </div>
      <div style={{ marginTop: 16, display: 'grid', gap: 16 }}>
        <div style={{ display: 'grid', gridTemplateColumns: '180px 1fr', alignItems: 'start', gap: 12, padding: '12px 0', borderBottom: '1px solid var(--border)' }}>
          <div style={{ color: 'var(--muted)' }}>旅行风格</div>
          <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8 }}>
            {TravelStyles.map(t => (
              <Chip key={t.code} active={(pref.travelStyle||[]).includes(t.code)} onClick={() => toggleArr('travelStyle', t.code)}>{t.label}</Chip>
            ))}
          </div>
        </div>
        <div style={{ display: 'grid', gridTemplateColumns: '180px 1fr', alignItems: 'start', gap: 12, padding: '12px 0', borderBottom: '1px solid var(--border)' }}>
          <div style={{ color: 'var(--muted)' }}>交通偏好</div>
          <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8 }}>
            {Transport.map(t => (
              <Chip key={t.code} active={(pref.transportPreference||[]).includes(t.code)} onClick={() => toggleArr('transportPreference', t.code)}>{t.label}</Chip>
            ))}
          </div>
        </div>
        <div style={{ display: 'grid', gridTemplateColumns: '180px 1fr', alignItems: 'center', gap: 12, padding: '12px 0', borderBottom: '1px solid var(--border)' }}>
          <div style={{ color: 'var(--muted)' }}>预算范围</div>
          <div>
            <input type="range" min={0} max={10000} step={50} value={pref.budgetRange} onChange={e => setPref(p => ({ ...p, budgetRange: Number(e.target.value) }))} style={{ width: '100%' }} />
            <div style={{ display: 'flex', justifyContent: 'space-between', color: 'var(--muted)', fontSize: 12 }}>
              <span>¥0</span><span>¥10000+</span>
            </div>
            <div style={{ textAlign: 'right', marginTop: 4 }}>¥{pref.budgetRange}</div>
          </div>
        </div>
        <div style={{ display: 'grid', gridTemplateColumns: '180px 1fr', alignItems: 'start', gap: 12, padding: '12px 0', borderBottom: '1px solid var(--border)' }}>
          <div style={{ color: 'var(--muted)' }}>住宿偏好</div>
          <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8 }}>
            {Accommodation.map(t => (
              <Chip key={t.code} active={(pref.accommodationType||[]).includes(t.code)} onClick={() => toggleArr('accommodationType', t.code)}>{t.label}</Chip>
            ))}
          </div>
        </div>
        <div style={{ display: 'grid', gridTemplateColumns: '180px 1fr', alignItems: 'start', gap: 12, padding: '12px 0', borderBottom: '1px solid var(--border)' }}>
          <div style={{ color: 'var(--muted)' }}>美食偏好</div>
          <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8 }}>
            {Food.map(t => (
              <Chip key={t.code} active={(pref.foodPreference||[]).includes(t.code)} onClick={() => toggleArr('foodPreference', t.code)}>{t.label}</Chip>
            ))}
          </div>
        </div>
        <div style={{ display: 'grid', gridTemplateColumns: '180px 1fr', alignItems: 'start', gap: 12, padding: '12px 0', borderBottom: '1px solid var(--border)' }}>
          <div style={{ color: 'var(--muted)' }}>旅行伙伴</div>
          <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8 }}>
            {Companions.map(t => (
              <Chip key={t.code} active={String(pref.travelCompanions) === t.code} onClick={() => setPref(p => ({ ...p, travelCompanions: t.code }))}>{t.label}</Chip>
            ))}
          </div>
        </div>
        <div style={{ display: 'grid', gridTemplateColumns: '180px 1fr', alignItems: 'start', gap: 12, padding: '12px 0', borderBottom: '1px solid var(--border)' }}>
          <div style={{ color: 'var(--muted)' }}>语言与时区</div>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
            <select value={pref.languagePreference} onChange={e => setPref(p => ({ ...p, languagePreference: e.target.value }))} style={{ height: 40, borderRadius: 12, border: '1px solid var(--border)', background: 'var(--card)', color: 'var(--text)', padding: '0 12px', outline: 'none' }}>
              {Languages.map(l => (<option key={l.code} value={l.code}>{l.label}</option>))}
            </select>
            <select value={pref.timezone} onChange={e => setPref(p => ({ ...p, timezone: e.target.value }))} style={{ height: 40, borderRadius: 12, border: '1px solid var(--border)', background: 'var(--card)', color: 'var(--text)', padding: '0 12px', outline: 'none' }}>
              {Timezones.map(t => (<option key={t.code} value={t.code}>{t.label}</option>))}
            </select>
          </div>
        </div>
        <div style={{ display: 'grid', gap: 12 , padding: '12px 0', borderBottom: '1px solid var(--border)' }}>
          <div style={{ color: 'var(--muted)', fontWeight: 600 }}>隐私设置</div>
          <div style={{ display: 'grid', gap: 12 }}>
            <div style={{ display: 'grid', gridTemplateColumns: '180px 1fr', alignItems: 'center', gap: 12}}>
              <div style={{ color: 'var(--muted)' }}>个人主页可见性</div>
              <select value={pref.privacySettings?.profile_visibility || 'public'} onChange={e => setPref(p => ({ ...p, privacySettings: { ...(p.privacySettings||{}), profile_visibility: e.target.value } }))} style={{ height: 40, borderRadius: 12, border: '1px solid var(--border)', background: 'var(--card)', color: 'var(--text)', padding: '0 12px', outline: 'none' }}>
                <option value="public">公开</option>
                <option value="friends_only">仅好友</option>
                <option value="private">私密</option>
              </select>
            </div>
            <div style={{ display: 'grid', gridTemplateColumns: '180px 1fr', alignItems: 'center', gap: 12}}>
              <div style={{ color: 'var(--muted)' }}>打卡可见性</div>
              <select value={pref.privacySettings?.checkin_visibility || 'friends_only'} onChange={e => setPref(p => ({ ...p, privacySettings: { ...(p.privacySettings||{}), checkin_visibility: e.target.value } }))} style={{ height: 40, borderRadius: 12, border: '1px solid var(--border)', background: 'var(--card)', color: 'var(--text)', padding: '0 12px', outline: 'none' }}>
                <option value="public">公开</option>
                <option value="friends_only">仅好友</option>
                <option value="private">私密</option>
              </select>
            </div>
            <div style={{ display: 'grid', gridTemplateColumns: '180px 1fr', alignItems: 'center', gap: 12}}>
              <div style={{ color: 'var(--muted)' }}>允许陌生人消息</div>
              <select value={String(pref.privacySettings?.allow_stranger_messages ?? false)} onChange={e => setPref(p => ({ ...p, privacySettings: { ...(p.privacySettings||{}), allow_stranger_messages: e.target.value === 'true' } }))} style={{ height: 40, borderRadius: 12, border: '1px solid var(--border)', background: 'var(--card)', color: 'var(--text)', padding: '0 12px', outline: 'none' }}>
                <option value="true">开启</option>
                <option value="false">关闭</option>
              </select>
            </div>
            <div style={{ display: 'grid', gridTemplateColumns: '180px 1fr', alignItems: 'center', gap: 12}}>
              <div style={{ color: 'var(--muted)' }}>显示在线状态</div>
              <select value={String(pref.privacySettings?.show_online_status ?? true)} onChange={e => setPref(p => ({ ...p, privacySettings: { ...(p.privacySettings||{}), show_online_status: e.target.value === 'true' } }))} style={{ height: 40, borderRadius: 12, border: '1px solid var(--border)', background: 'var(--card)', color: 'var(--text)', padding: '0 12px', outline: 'none' }}>
                <option value="true">开启</option>
                <option value="false">关闭</option>
              </select>
            </div>
          </div>
        </div>
        <div style={{ display: 'grid', gap: 12}}>
          <div style={{ color: 'var(--muted)', fontWeight: 600 }}>通知设置</div>
          <div style={{ display: 'grid', gap: 12 }}>
            <div style={{ display: 'grid', gridTemplateColumns: '180px 1fr', alignItems: 'center', gap: 12}}>
              <div style={{ color: 'var(--muted)' }}>消息通知</div>
              <select value={String(pref.notificationSettings?.msg_notify ?? true)} onChange={e => setPref(p => ({ ...p, notificationSettings: { ...(p.notificationSettings||{}), msg_notify: e.target.value === 'true' } }))} style={{ height: 40, borderRadius: 12, border: '1px solid var(--border)', background: 'var(--card)', color: 'var(--text)', padding: '0 12px', outline: 'none' }}>
                <option value="true">开启</option>
                <option value="false">关闭</option>
              </select>
            </div>
            <div style={{ display: 'grid', gridTemplateColumns: '180px 1fr', alignItems: 'center', gap: 12 }}>
              <div style={{ color: 'var(--muted)' }}>点赞通知</div>
              <select value={String(pref.notificationSettings?.like_notify ?? true)} onChange={e => setPref(p => ({ ...p, notificationSettings: { ...(p.notificationSettings||{}), like_notify: e.target.value === 'true' } }))} style={{ height: 40, borderRadius: 12, border: '1px solid var(--border)', background: 'var(--card)', color: 'var(--text)', padding: '0 12px', outline: 'none' }}>
                <option value="true">开启</option>
                <option value="false">关闭</option>
              </select>
            </div>
            <div style={{ display: 'grid', gridTemplateColumns: '180px 1fr', alignItems: 'center', gap: 12}}>
              <div style={{ color: 'var(--muted)' }}>关注通知</div>
              <select value={String(pref.notificationSettings?.follow_notify ?? true)} onChange={e => setPref(p => ({ ...p, notificationSettings: { ...(p.notificationSettings||{}), follow_notify: e.target.value === 'true' } }))} style={{ height: 40, borderRadius: 12, border: '1px solid var(--border)', background: 'var(--card)', color: 'var(--text)', padding: '0 12px', outline: 'none' }}>
                <option value="true">开启</option>
                <option value="false">关闭</option>
              </select>
            </div>
          </div>
        </div>
        <div style={{ display: 'flex', justifyContent: 'flex-end', gap: 12 }}>
          <Button variant="outline" onClick={reset} style={{ border: '1px solid var(--text)', color: 'var(--text)' }}>重置</Button>
          <Button onClick={save} style={{ background: 'var(--text)', color: 'var(--bg)', border: '1px solid var(--text)' }}>保存更改</Button>
        </div>
      </div>
    </Card>
  );
};

const Placeholder = ({ title }) => (
  <Card>
    <div style={{ color: 'var(--text)', fontWeight: 800, fontSize: 18 }}>{title}</div>
    <div style={{ marginTop: 12, color: 'var(--muted)' }}>暂无内容</div>
  </Card>
);

const Profile = () => {
  const { user } = useAuth();
  const [tab, setTab] = useState('info');
  const narrow = useMemo(() => typeof window !== 'undefined' ? window.innerWidth <= 900 : false, []);

  return (
    <div style={{ display: 'grid', gridTemplateColumns: narrow ? '1fr' : '240px 1fr', gap: 16, padding: 16 }}>
      <Sidebar current={tab} onChange={setTab} user={user} />
      <div style={{ display: 'grid', gap: 16 }}>
        {tab === 'info' && <ProfileInfo />}
        {tab === 'prefs' && <TravelPreferences />}
        {tab === 'checkin' && <Placeholder title="打卡记录" />}
        {tab === 'posts' && <Placeholder title="发布帖子" />}
        {tab === 'collections' && <Placeholder title="收藏内容" />}
        {tab === 'trash' && <Placeholder title="回收站" />}
      </div>
    </div>
  );
};

export default Profile;
